import random
import time
import pytest  # 引入 pytest

# 冒泡排序
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        swapped = False
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:  # 如果没有交换，说明已经有序
            break
    return arr

# 选择排序
def selection_sort(arr):
    n = len(arr)
    for i in range(n):
        min_idx = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_idx]:
                min_idx = j
        if min_idx != i:  # 只有在找到新最小值时才交换
            arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr

# 归并排序
def merge_sort(arr):
    if len(arr) > 1:
        mid = len(arr) // 2
        left_half = arr[:mid]
        right_half = arr[mid:]

        merge_sort(left_half)
        merge_sort(right_half)

        i = j = k = 0
        while i < len(left_half) and j < len(right_half):
            if left_half[i] < right_half[j]:
                arr[k] = left_half[i]
                i += 1
            else:
                arr[k] = right_half[j]
                j += 1
            k += 1

        while i < len(left_half):
            arr[k] = left_half[i]
            i += 1
            k += 1
        while j < len(right_half):
            arr[k] = right_half[j]
            j += 1
            k += 1

    return arr

# 生成随机数组
def generate_random_array(size):
    return random.sample(range(1, 500001), size)

# 在pytest中测试排序算法
@pytest.mark.parametrize("size", [1000, 10000, 100000])  # 参数化测试
def test_sorting_algorithms(size):
    print(f"\nTesting with array size: {size}")

    arr = generate_random_array(size)

    # 冒泡排序
    arr_copy = arr.copy()
    start_time = time.time()
    bubble_sort(arr_copy)
    bubble_time = time.time() - start_time
    print(f"Bubble Sort Time:     {bubble_time:.6f} seconds")

    # 选择排序
    arr_copy = arr.copy()
    start_time = time.time()
    selection_sort(arr_copy)
    selection_time = time.time() - start_time
    print(f"Selection Sort Time: {selection_time:.6f} seconds")

    # 归并排序
    arr_copy = arr.copy()
    start_time = time.time()
    merge_sort(arr_copy)
    merge_time = time.time() - start_time
    print(f"Merge Sort Time:     {merge_time:.6f} seconds")

# 如果直接运行此文件，可以执行测试
if __name__ == "__main__":
    pytest.main()